#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>
#include <filesystem>

extern "C" void* BeginDecode(void *obj, int code, void (*decode)(void *obj, 
	unsigned char *ydata, int ylen, unsigned char *udata, int ulen, 
    unsigned char *vdata, int vlen, int width, int height, int frame_index));
extern "C" void ImageDecode(void *handle, unsigned char *data, int len);
extern "C" void EndDecode(void *handle);

#include <opencv2/core.hpp>
#include <opencv2/opencv.hpp>

void show(unsigned char* y,int yl,unsigned char*u,int ul,unsigned char* v,int vl,int w,int h)
{
	std::vector<unsigned char> buf;
	cv::Mat image_data = cv::Mat(h*3/2,w,CV_8UC1);
	for (int i = 0; i < h&&y!=nullptr; i++) 
		buf.insert(buf.end(),y+i*yl,y+i*yl+w);
	for (int i = 0; i < h / 2&&u!=nullptr; i++) 
		buf.insert(buf.end(),u+i*ul,u+i*ul+w/2);
	for (int i = 0; i < h / 2&&v!=nullptr; i++) 
		buf.insert(buf.end(),v+i*vl,v+i*vl+w/2);
	memcpy(image_data.data, &buf[0], buf.size());

	cv::Mat image_data_rgb;
	cvtColor(image_data, image_data_rgb, cv::COLOR_YUV2RGB_I420);
	cv::imwrite("test.bmp",image_data_rgb);
}

int main()
{
    void* pDecode = nullptr;
    unsigned char data[1024*4] = {0};
    FILE* fl = fopen("encode.h264","rb");
    pDecode = BeginDecode(nullptr,27,[](void* obj, unsigned char *ydata, int ylen, unsigned char *udata, int ulen, 
	    unsigned char *vdata, int vlen, int width, int height, int frame_index){
        printf("------");
        show(ydata,ylen,udata,ulen,vdata,vlen,width,height);
    });
    while (fl!=nullptr)
    {
        size_t len = fread(data, 1, sizeof(data), fl);
        ImageDecode(pDecode,data, (len>sizeof(data)?sizeof(data):len));
        if (len < sizeof(data))	{
            break;
        }
    }
    EndDecode(pDecode);
    fclose(fl);
}